/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package network;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.ByteBuffer;

/**
 *
 * @author lupomobile
 */
public class TLV {

    private int type; //4 byte per il tipo 256 valori da -128 a 127
    private int length;
    private byte[] value;
    public static final int AUTH_INIT_SEND_P = 11;
    public static final int AUTH_INIT_SEND_G = 12;
    public static final int AUTH_START = 2;
    public static final int AUTH_RESPONCE = 3;
    public static final int AUTH_RESPONCE_SIGN = 4;
    public static final int SESSION_END = 99;
    public static final int ABORT_SESSION = 666;

    public TLV(int t, byte[] v) {
        type = t;
        length = v.length;
        value = v;
    }

    public TLV(byte[] pack) {
        ByteBuffer buff = ByteBuffer.wrap(pack);
        type = buff.getInt(0);
        length = buff.getInt(4);
        value = new byte[length];
        buff.position(8); //Il ByteBuffer si comporta come una pila con certi metodi
        buff.get(value, 0, length);
    }

    public byte[] generatePackage() {
        int size = 4 + 4 + value.length;
        ByteBuffer pack = ByteBuffer.allocate(size);
        ByteBuffer type_b = ByteBuffer.allocate(4);
        ByteBuffer length_b = ByteBuffer.allocate(4);
        type_b.putInt(type);
        length_b.putInt(length);

        pack.put(type_b.array());
        pack.put(length_b.array());
        pack.put(value);
        return pack.array();
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public byte[] getValue() {
        return value;
    }

    public void setValue(byte[] value) {
        this.value = value;
    }
    
    public static TLV fetchPackage(Socket c) {
        try {
            InputStream ingresso = c.getInputStream();
            byte[] temp = new byte[4];
            int type;
            int length;
            byte[] value;

            ingresso.read(temp, 0, 4);

            // Controllo di tipo
            type = ByteBuffer.wrap(temp).getInt();
            ingresso.read(temp, 0, 4);
            length = ByteBuffer.wrap(temp).getInt();
            value = new byte[length];
            ingresso.read(value, 0, length);

            return new TLV(type, value);
        } catch (IOException e) {
        }

        return null;
    }
}
